<template>
  <gui-page ref="guiPage" :fullPage="true">
    <template v-slot:gBody>
      <view class="gui-flex1 gui-flex gui-column">
        <swiper
          :current="currentIndex"
          @change="swiperChange"
          :style="{ height: swiperHeight + 10 + 'px', width: '750rpx' }"
        >
          <swiper-item class="gui-bg-gray">
            <!-- <view class="gui-relative gui-flex gui-bg-white">
							<gui-switch-navigation-shopping style="width: 100%" :size="150" lineHeight="60rpx"
								:activeLineClass="['gui-xhs-red']" :items="categoryTabs" activeDirection="center"
								textAlign="center" :currentIndex="currentCategoryIndex" @change="navchangeCategories">
							</gui-switch-navigation-shopping>
						</view> -->
            <view id="content-wrap1" style="padding: 0 15rpx">
              <view
                class="gui-flex gui-row gui-space-between"
                style="margin-top: 15rpx"
              >
                <view
                  class="gui-waterfall-item"
                  v-for="(lists, index1) in noteList1"
                  :key="index1"
                >
                  <view
                    :id="'waterfall1' + index1 + index2"
                    @tap="goDetail(notes)"
                    class="gui-waterfall-items gui-bg-white gui-border-radius gui-relative"
                    style="overflow: hidden; padding-bottom: 8rpx"
                    v-for="(notes, index2) in lists"
                    :key="index2"
                  >
                    <text
                      v-if="notes.noteType === '1' || notes.noteType === 1"
                      style="width: 130rpx"
                      class="gui-card-tip gui-border-radius gui-absolute-rt gui-text-small gui-color-white gui-bg-black-opacity5"
                      >图文笔记</text
                    >
                    <text
                      v-if="notes.noteType === '2' || notes.noteType === 2"
                      style="width: 130rpx"
                      class="gui-card-tip gui-border-radius gui-absolute-rt gui-text-small gui-color-white gui-bg-black-opacity5"
                      >视频笔记</text
                    >
                    <text
                      v-if="notes.noteType === '3' || notes.noteType === 3"
                      style="width: 130rpx"
                      class="gui-card-tip gui-border-radius gui-absolute-rt gui-text-small gui-color-white gui-bg-black-opacity5"
                      >音乐笔记</text
                    >

                    <gui-image
                      @imgLoad="imgLoad"
                      :src="notes.firstPicture"
                      :width="355"
                    ></gui-image>
                    <view
                      class="gui-text gui-primary-text xhs-margin-top-15 xhs-font30"
                      style="color: #333333; margin-left: 16rpx"
                    >
                      <text>{{ notes.noteTitle }}</text>
                    </view>
                    <view
                      class="gui-flex gui-row gui-space-between xhs-margin-top-15"
                    >
                      <view>
                        <image
                          style="width: 28px; height: 28px; margin-left: 16rpx"
                          class="gui-list-image ucenter-face-image"
                          :src="notes.authorAvatar"
                          mode="aspectFill"
                        ></image>
                      </view>
                      <view
                        style="
                          font-size: 24rpx;
                          color: #5a5a5a;
                          line-height: 60rpx;
                          width: 200rpx;
                        "
                      >
                        <text>{{ notes.authorName }}</text>
                      </view>

                      <view
                        style="
                          margin-right: 16rpx;
                          color: #acacac;
                          line-height: 42rpx;
                          font-size: 28rpx;
                          text-align: center;
                        "
                      >
                        <text
                          :class="[
                            'gui-icons',
                            'gui-block',
                            'ranking-lists-zan-icon',
                            notes.isUp ? 'zan-active ' : '',
                          ]"
                          >{{ notes.isUp ? "&#xe605;" : "&#xe6ad;"
                          }}<text style="color: #5a5a5a; margin-left: 5rpx">
                            {{ notes.upCount }}</text
                          >
                        </text>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
              <view style="padding: 20rpx 0">
                <gui-loadmore
                  v-show="currentIndex == 0"
                  ref="loadmorecom1"
                  :status="1"
                ></gui-loadmore>
              </view>
            </view>
          </swiper-item>
        </swiper>
      </view>
    </template>
  </gui-page>
</template>
<script>
import graceJS from "@/Grace6/js/grace.js";
import getWebSocketClient from "@/Grace6/js/ws";
// 模拟数据
import dataObj from "@/Grace6/demoData/data.js";
import GuiImage from "@/Grace6/components/gui-image.vue";
import graceRequestConfig from "@/custom/graceRequestConfig.js";
import GuiLoadmore from "@/Grace6/components/gui-loadmore.vue";
import GuiPage from "@/Grace6/components/gui-page.vue";
import commonMixin from "@/mixin/commonMinxin";
export default {
  mixins: [commonMixin],
  props: ["comPage"],
  components: {
    GuiPage,
    GuiLoadmore,
    GuiImage,
  },

  data() {
    return {
      showPromotion: false,
      speakerMsgs: [
        {
          title: "商务　微信: dadait24　qq: 727869402",
        },
      ],
      loaded: false,
      // 全屏 loading
      // 顶部选项卡标签
      tabs: [
        {
          id: 1,
          name: "关注",
        },
      ],
      // 顶部选项卡标签 选中选项的 索引
      currentIndex: 0,
      swiperHeight: 0,
      defaultSwiperHeight: 0,
      noteList1: [[], []],
      // 用于记录是否有 api 请求正在执行
      apiLoadingStatus1: false,
      page1: 1,
      loadMoreTimer1: null,
      categoryTabs: [],
      currentCategoryIndex: 0,
      isFixed: false,
      menuHeight: 60,
      starFolderId: "",
      // 添加滚动相关的状态
      scrollTop: 0,
      windowHeight: 0,
      contentHeight: 0,
      reachBottomDistance: 50, // 触底距离
      isLoadingMore: false, // 是否正在加载更多
    };
  },

  computed: {
    categoryNames() {
      return this.categoryTabs.map((tab) => tab.name);
    },
  },
  watch: {
    comPage(newVal, OldVal) {
      console.log(newVal, "很久很久很久");
      this.page1 = newVal;
      this.getNotes1();
    },
    currentIndex(newVal, OldVal) {
      if (this.currentIndex != 1) {
        uni.app.checkLogin();
      }
      this.$nextTick(() => {
        //切换时刷新高度
        this.setSwiperHeight(this.currentIndex + 1);
      });
    },
  },
  methods: {
    searchNote() {
      uni.navigateTo({
        url: "/pages/search/search",
      });
    },
    //格式化时间
    formatDate(date) {},

    //点赞笔记
    upNote(notes) {
      uni.app.post("/auth/upNote", notes, "json", "", (res) => {
        console.log(res.data);
        if (res.data) {
          notes.isUp = true;
          notes.upCount++;
        } else {
          notes.isUp = false;
          notes.upCount--;
        }
      });
    },
    //图片加载成功后重新 计算高度防止高度不够无法滑动
    imgLoad() {
      this.$nextTick(() => {
        this.setSwiperHeight(this.currentIndex + 1);
      });
    },
    //计算高度
    setSwiperHeight(i) {
      var swiperHeightTimer = null;
      if (swiperHeightTimer != null) {
        clearTimeout(swiperHeightTimer);
      }
      swiperHeightTimer = setTimeout(() => {
        // console.log('设置了高度')
        let element = "#content-wrap" + i.toString();
        // console.log(element)
        let query = uni.createSelectorQuery().in(this);
        query.select(element).boundingClientRect();
        query.exec((res) => {
          // console.log(res)
          if (res && res[0]) {
            // console.log('当前Swiper'+ i +'高度' + res[0].height)
            if (
              res[0].height == 0 ||
              res[0].height < this.defaultSwiperHeight
            ) {
              // console.log('当前高度小于默认高度' + this.defaultSwiperHeight)
              this.swiperHeight = this.defaultSwiperHeight;
            } else {
              this.swiperHeight = res[0].height;
            }
            // console.log('赋值了高度 当前currentIndex+1=' + (this.currentIndex+1) +' getNodes监听的数据' + this.swiperHeight)
          }
        });
      }, 100);
    },
    navchange: function (index) {
      this.currentIndex = index;
    },
    swiperChange: function (e) {
      var index = e.detail.current;
      this.currentIndex = index;
    },
    //进入详情
    goDetail(e) {
      let url;
      let checkLogin = uni.app.checkLogin();
      if (checkLogin) {
        // 确保noteType是字符串类型
        const noteType = String(e.noteType);
        if (noteType === "1") {
          url = `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/notes/detail/detail?noteId=${e.noteId}`;
          this.goPage(url);
        } else if (noteType === "2") {
          ((url = `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/notes/videoDetail/videoDetail?noteId=${e.noteId}`),
            this.goPage(url));
        } else if (noteType === "3") {
          url: (`https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/notes/musicDetail/musicDetail?noteId=${e.noteId}`,
            this.goPage(url));
          // uni.navigateTo({
          // 	url: "/pages/notes/musicDetail/musicDetail?noteId=" + e.noteId,
          // });
        } else {
          console.log("未知笔记类型:", noteType);
        }
      }
    },
    goPage(url) {
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          let ddd = {
            hideNavBar: "1",
            hideTotalNavBar: "1",
            hideBottomSafeBar: "1",
            url: url,
          };
          let d = JSON.stringify(ddd);
          console.log(d, "都是对的");
          window.AndroidBridge.pushNewWebVC(d);
          console.log("运行Android上");
          break;
        case "ios":
          window.webkit.messageHandlers.pushNewWebVC.postMessage({
            hideNavBar: "1",
            hideTotalNavBar: "1",
            hideBottomSafeBar: "1",
            url: url,
          });
          break;
        default:
          console.log("运行在开发者工具上");
          break;
      }
    },
    getNotes1(isReload) {
      console.log("开始加载笔记，第" + this.page1 + "页");
      this.apiLoadingStatus1 = true;
      const that = this;

      // 显示加载提示
      if (!isReload) {
        uni.showLoading({
          title: "加载中...",
          mask: false,
        });
      }

      let data = {
        starFolderId: 1,
        limit: 10,
        offset: this.page1, // offset 参数就是页码
        authorId: uni.getStorageSync("userId"),
      };

      // 根据分类过滤内容
      if (this.categoryTabs.length > 0 && this.currentCategoryIndex > 0) {
        // 这里把分类ID作为noteType参数传递
        data.noteType = this.categoryTabs[this.currentCategoryIndex].id;
      }

      console.log("请求参数:", JSON.stringify(data));

      // 根据环境判断是否处理错误
      const handleError = (err) => {
        console.error("API请求失败:", err);
        that.apiLoadingStatus1 = false;
        uni.hideLoading();
        if (that.$refs.loadmorecom1) {
          that.$refs.loadmorecom1.stoploadmore();
        }
        uni.showToast({
          title: "加载失败，请重试",
          icon: "none",
        });
        if (isReload) {
          uni.stopPullDownRefresh();
        }
      };

      uni.app.post("/blog/note/getAuthorNotes", data, "", "", (res) => {
        // 隐藏加载提示
        uni.hideLoading();

        // 检查返回数据有效性
        if (!res) {
          return handleError("返回数据为空");
        }

        if (res.code == 2000) {
          console.log("getNotes1当前页" + that.page1);
          console.log("总页数" + res.data.pages);

          // 获取记录列表和分页信息
          let notes = res.data.records || [];
          let totalPages = res.data.pages || 1;

          console.log("本次获取数据条数:" + (notes ? notes.length : 0));

          if (that.page1 <= totalPages) {
            // 如果没有获取到数据或数据为空
            if (!notes || notes.length === 0) {
              console.log("没有更多数据了");
              that.apiLoadingStatus1 = false;
              if (that.$refs.loadmorecom1) {
                that.$refs.loadmorecom1.nomore();
              }
              if (isReload) {
                uni.stopPullDownRefresh();
              }
              return;
            }

            // 平衡左右两列数据，使页面更美观
            for (var i = 0; i < notes.length; i++) {
              const leftColHeight = that.noteList1[0].reduce(
                (sum, item) => sum + 1,
                0,
              );
              const rightColHeight = that.noteList1[1].reduce(
                (sum, item) => sum + 1,
                0,
              );

              if (leftColHeight <= rightColHeight) {
                that.noteList1[0].push(notes[i]);
              } else {
                that.noteList1[1].push(notes[i]);
              }
            }

            // 重新计算高度
            this.$nextTick(() => {
              this.setSwiperHeight(1);
            });

            // 判断是否还有更多数据
            if (that.page1 >= totalPages) {
              console.log("已加载全部数据");
              if (that.$refs.loadmorecom1) {
                that.$refs.loadmorecom1.nomore();
              }
            } else {
              console.log("还有更多数据，下一页:" + (that.page1 + 1));
              that.page1 = that.page1 + 1;
              if (that.$refs.loadmorecom1) {
                that.$refs.loadmorecom1.stoploadmore();
              }
            }

            that.apiLoadingStatus1 = false;
            that.isLoadingMore = false;
          } else {
            // 如果请求的页数超过总页数，说明没有更多数据
            that.apiLoadingStatus1 = false;
            that.isLoadingMore = false;
            if (that.$refs.loadmorecom1) {
              that.$refs.loadmorecom1.nomore();
            }
          }

          if (isReload) {
            uni.stopPullDownRefresh();
          }
        } else {
          that.isLoadingMore = false;
          handleError(res);
        }
      });
    },
    navchangeCategories(index) {
      this.currentCategoryIndex = index;
      this.page1 = 1;
      this.noteList1 = [[], []];
      if (this.$refs.loadmorecom1) {
        this.$refs.loadmorecom1.stoploadmore();
      }
      this.getNotes1(true);
    },

    // 加载更多数据的方法
    loadMoreData() {
      console.log("执行 loadMoreData 方法");

      // 防止重复加载
      if (this.apiLoadingStatus1 || this.isLoadingMore) {
        console.log("API正在加载中，忽略加载请求");
        return;
      }

      this.isLoadingMore = true;

      // 保证只执行一次加载
      if (this.loadMoreTimer1 != null) {
        clearTimeout(this.loadMoreTimer1);
      }

      this.loadMoreTimer1 = setTimeout(() => {
        // 检查加载状态
        var status = this.$refs.loadmorecom1
          ? this.$refs.loadmorecom1.loadMoreStatus
          : 0;
        console.log("loadMoreStatus:", status);

        if (status != 0) {
          console.log("已经在加载中或者没有更多数据了");
          this.isLoadingMore = false;
          return;
        }

        // 显示加载中状态
        if (this.$refs.loadmorecom1) {
          this.$refs.loadmorecom1.loading();
        }
        console.log("触发加载更多，准备调用 getNotes1");

        // 加载数据
        this.getNotes1();
      }, 50);
    },
  },
  //下拉刷新
  onPullDownRefresh: function () {
    if (this.apiLoadingStatus1) {
      uni.stopPullDownRefresh();
      return;
    }
    this.page1 = 1;
    this.noteList1 = [[], []];
    this.getNotes1(true);
  },
  onShow() {
    console.log("onShow");
    console.log("this.loaded" + this.loaded);
    //证明不是第一次进页面了 刷新当前页

    this.$nextTick(() => {
      // 因为在appvue 无法获取tabbar
      const wsClient = getWebSocketClient();
      //获取总数
      uni.app.getTotalUnReadCount();
      wsClient.onSocketMessageCallback = (res) => {
        if (
          res.handlerType == "1" ||
          res.handlerType == "2" ||
          res.handlerType == "3" ||
          res.handlerType == "4"
        ) {
          //点赞收藏关注
          uni.app.getTotalUnReadCount();
        }
        if (res.handlerType == "5") {
          //获取总数
          uni.app.getTotalUnReadCount();
        }
        if (res.handlerType == "9") {
          //设置角标
          uni.app.setMessageTabBarBadge(res.body.totalUnReadCount);
        }
      };

      // 页面显示时更新高度
      setTimeout(() => {
        this.setSwiperHeight(this.currentIndex + 1);
      }, 300);
    });
  },
  created() {
    // 初始化分类
    this.categoryTabs = [
      {
        name: "全部",
        id: "",
      },
      {
        name: "图文",
        id: "1",
      },
      {
        name: "视频",
        id: "2",
      },
      {
        name: "音乐",
        id: "3",
      },
    ];
    this.getNotes1();

    // 确保初始化高度
    this.$nextTick(() => {
      // 设置一个初始高度
      this.swiperHeight =
        uni.getSystemInfoSync().windowHeight - uni.upx2px(110);
    });
  },
  onLoad: function (e) {
    this.showPromotion = graceRequestConfig.showPromotion;

    this.$nextTick(() => {
      const query = uni.createSelectorQuery().in(this);
      query
        .select("#header")
        .boundingClientRect((data) => {
          if (data) {
            // console.log('header')
            // console.log( data )
          }
        })
        .exec();
      this.getNotes1();
      this.loaded = true;

      const user = uni.app.getStorage("user");
      console.log("user:" + JSON.stringify(user));

      // 确保初始化高度
      this.swiperHeight =
        this.windowHeight || uni.getSystemInfoSync().windowHeight;
    });
  },
  onReachBottom: function () {
    console.log("触发 onReachBottom 事件");
    this.loadMoreData();
  },

  mounted: function () {
    var mountedTimer = null;
    if (mountedTimer != null) {
      clearTimeout(mountedTimer);
    }
    mountedTimer = setTimeout(() => {
      // 01. 获取页面主体高度
      graceJS.getRefs("guiPage", this, 0, (ref) => {
        ref.getDomSize("guiPageBody", (e) => {
          this.swiperHeight = e.height - uni.upx2px(110) - 92.8; //导航栏高度
          this.defaultSwiperHeight = e.height - uni.upx2px(110);

          // 获取窗口高度
          this.windowHeight = uni.getSystemInfoSync().windowHeight;
          console.log(
            "页面高度:",
            this.swiperHeight,
            "窗口高度:",
            this.windowHeight,
          );
        });
      });
    }, 100);
  },

  // 修改 onPageScroll 方法，确保它能够正确触发加载
  onPageScroll: function (e) {
    // 记录当前滚动位置，用于调试
    this.scrollTop = e.scrollTop;
    console.log("页面滚动位置:", this.scrollTop);

    // 检查是否到达底部
    const windowHeight =
      this.windowHeight || uni.getSystemInfoSync().windowHeight;
    const pageHeight = this.swiperHeight + 10;

    // 如果滚动位置 + 窗口高度 + 预加载距离 >= 页面高度，触发加载更多
    if (this.scrollTop + windowHeight + 10 >= pageHeight) {
      console.log("检测到接近底部，触发加载更多");
      if (!this.apiLoadingStatus1 && !this.isLoadingMore) {
        this.loadMoreData();
      }
    }
  },
};
</script>
<style lang="scss" scoped>
/*数值越大屏幕中边距越小 左右模块的宽度*/
.gui-waterfall-item {
  width: 355rpx;
}

.gui-waterfall-items {
  margin-bottom: 15rpx;
}

.gui-block {
  margin-top: 10rpx;
}

/* #ifdef MP */
.search-icon {
  top: 100rpx !important;
  right: 280rpx !important;
}

/* #endif */

/* #ifdef APP-PLUS */
.search-icon {
  top: 80rpx !important;
  right: 120rpx !important;
}

/* #endif */
</style>
